package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.bson.Document;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcPreparedStatement;
import org.budo.mongo.jdbc.driver.BudoMongoJdbcResultSetMetaData;
import org.budo.mongo.jdbc.driver.resultset.MongoCursorResultSet;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

/**
 * @author li
 */
public class MongoFindStatement extends AbstractMongoStatement {
    private static final Logger log = Slf4j.getLogger();

    public void execute(PreparedStatement preparedStatement) throws SQLException{
        BudoMongoJdbcPreparedStatement mongoPreparedStatement = (BudoMongoJdbcPreparedStatement) preparedStatement;
        MongoCollection mongoCollection = this.getMongoCollection(mongoPreparedStatement);
        Map<String, Object> statementDocument = this.getStatementDocumentWithParameterValues(mongoPreparedStatement.getParameterMap());

        log.debug("execute(), statementDocument={}, sql={}, parameterMap={}", statementDocument, this.sql(), mongoPreparedStatement.getParameterMap());

        Map<String, Object> whereDocument = (Map<String, Object>) statementDocument.get(WHERE);

        FindIterable<Document> findIterable;
        if (null == whereDocument) {
            findIterable = mongoCollection.find();
        } else {
            findIterable = mongoCollection.find(new Document(whereDocument));
        }

        Map<String, Object> sortDocument = (Map<String, Object>) statementDocument.get(SORT);
        if (null != sortDocument && !sortDocument.isEmpty()) {
            findIterable = findIterable.sort(new Document(sortDocument));
        }

        Map<String, Object> pageDocument = (Map<String, Object>) statementDocument.get(PAGE);
        if (null != pageDocument && !pageDocument.isEmpty()) {
            Object skip = pageDocument.get(PAGE_SKIP);
            if (null != skip && !"".equals(skip)) {
                findIterable = findIterable.skip(new Integer(skip.toString()));
            }
            Object limit = pageDocument.get(PAGE_LIMIT);
            if (null != limit && !"".equals(limit)) {
                findIterable = findIterable.limit(new Integer(limit.toString()));
            }
        }

        MongoCursorResultSet mongoJdbcResultSet = new MongoCursorResultSet();
        MongoCursor<Document> iterator = findIterable.iterator();

        // 先把第一行读出来，得到列信息，然后暂存第一行
        if (iterator.hasNext()) {
            Document firstDoc = iterator.next();
            BudoMongoJdbcResultSetMetaData metaData = new BudoMongoJdbcResultSetMetaData(firstDoc.keySet().toArray(new String[firstDoc.size()]));
            mongoJdbcResultSet.setMetaData(metaData);
            mongoJdbcResultSet.setMongoCursor(iterator);
            mongoJdbcResultSet.setNextDocument(firstDoc);
        } else {
            BudoMongoJdbcResultSetMetaData metaData = this.getResultSetMetaData();
            mongoJdbcResultSet.setMetaData(metaData);
            mongoJdbcResultSet.setMongoCursor(iterator);
        }

        mongoPreparedStatement.resultSet(mongoJdbcResultSet);
    }
}